package com.itheima.util;

public class QuickSort {
    public static int[] quickSort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return arr;
        }
        quickSortHelper(arr, 0, arr.length - 1);
        return arr;
    }

    private static void quickSortHelper(int[] arr, int left, int right) {
        if (left < right) {
            int[] partition = partition(arr, left, right);
            quickSortHelper(arr, left, partition[0] - 1);
            quickSortHelper(arr, partition[1] + 1, right);
        }
    }

    // 实现适用于数组的swap方法
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    private static int[] partition(int[] arr, int left, int right) {
        int less = left - 1;
        int more = right;
        int target = arr[right];

        while (left < more) {
            if (arr[left] < target) {
                swap(arr, ++less, left++);
            } else if (arr[left] > target) {
                swap(arr, --more, left);
            } else {
                left++;
            }
        }
        swap(arr, more, right);
        return new int[]{less + 1, more};
    }
}
